package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.MemberRespVo;
import com.atguigu.common.utils.JwtUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.utils.ValidatitorUtils;
import com.atguigu.common.vo.LoginUserVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 注册
     *
     * @param vo
     * @return
     */
    @PostMapping("/regist")
    public R regist(@RequestBody UserRegistVo vo) {
        //数据校验
        ValidatitorUtils.validateEntity(vo);

        //todo 验证码存到redis中，key是手机号，value是验证码，这里跳过该逻辑

        //远程调用注册逻辑
        R r = memberFeignService.regist(vo);
        return r;
    }

    /**
     * 登录,返回token
     *
     * @param vo
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody UserLoginVo vo, HttpServletRequest request) {
        //数据校验
        ValidatitorUtils.validateEntity(vo);

        R login = memberFeignService.login(vo);

        if (login.getCode() == 0) {
            MemberRespVo data = login.getData(new TypeReference<MemberRespVo>() {
            });

            //用jwtToken替代Session
            //session.setAttribute(AuthServerConstant.LOGIN_USER,data);

            //封装登录的用户信息并生成token，返回给客户端
            LoginUserVo userVo = new LoginUserVo();
            BeanUtils.copyProperties(data,userVo);
            String jwtToken = JwtUtils.getJwtToken(userVo);


            Map<String,String> map=new HashMap<>();
            map.put("token",jwtToken);
            return R.ok().setData(map);
        }

        return login;
    }
}
